﻿using System;
using System.Linq;
using System.Web.DynamicData;
using System.Web.UI;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;

namespace DD_Extensions
{
    public partial class ImageUpload : FieldTemplateUserControl
    {
        private String ATTRIBUTE_MISSING_ERROR = "FileImage FieldTemplate for column {0} requires a ImageUploadAttribute";

        public override Control DataControl
        {
            get { return Image1; }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            //check if image exists
            if (FieldValue == null)
            {
                return;
            }

            var fileImage = MetadataAttributes.GetAttribute<ImageUploadAttribute>();

            // make sure we have an attribute
            if (fileImage == null)
                throw new InvalidOperationException(String.Format(ATTRIBUTE_MISSING_ERROR, Column.Name));

            // get primary key value
            var primaryKeyValue = Table.GetPrimaryKeyString(Row);

            Image1.ImageUrl = UploadExtensionMethods.GetUploadPath(fileImage.FileUploadPath, Table.Name, primaryKeyValue, Column.Name) + "/" + FieldValueString;

            var imageFormat = MetadataAttributes.GetAttribute<ImageFormatAttribute>();
            if (imageFormat != null)
            {
                if (imageFormat.DisplayWidth > 0)
                    Image1.Width = imageFormat.DisplayWidth;
                if (imageFormat.DisplayHeight > 0)
                    Image1.Height = imageFormat.DisplayHeight;
            }
        }
    }
}